package a07_二叉树;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * <p>
 * a03_层序遍历01_二叉树的层序遍历
 * </p>
 *
 * @author flyduck
 * @since 2024-08-20
 */
public class a05_层序遍历07_填充每个节点的下一个右侧节点指针 {

    public static void main(String[] args) {
//        TreeNode root = new TreeNode(
//                6,
//                new TreeNode(4,new TreeNode(1),new TreeNode(3)),
//                new TreeNode(7,new TreeNode(5),new TreeNode(8)));
        TreeNode root = new TreeNode(
                6,
                new TreeNode(4),
                new TreeNode(7,new TreeNode(5),new TreeNode(8)));

    }

    public Node connect(Node root) {
        if (root == null) {
            return root;
        }

        Queue<Node> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()){
            int popSize = queue.size();
            Node prev = null;
            while (popSize > 0) {
                Node poll = queue.poll();
                if(prev != null){
                    prev.next = poll;
                }
                prev = poll;
                if (poll.left != null) {
                    queue.add(poll.left);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                }
                popSize--;
            }
        }
        return root;

    }


}

